package com.duowan.cms.action.article;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.duowan.cms.common.domain.Page;
import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.DateUtil;
import com.duowan.cms.common.util.PathUtil;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.dto.article.Article4TagListInfo;
import com.duowan.cms.dto.article.Article4TagListSearchCriteria;
import com.duowan.cms.dto.article.Article4TagListSearchCriteria.Article4TagListOrderBy;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.dto.tag.TagInfo;
import com.duowan.cms.dto.user.UserInfo;
import com.duowan.cms.service.article.Article4TagListService;
import com.duowan.cms.service.channel.ChannelService;
import com.duowan.cms.service.tag.TagService;

/**
 * 处理与文章列表相关的页面请求
 * <p>作　　者：黄均杨
 * <p>完成日期：2012-12-28
 */
@Controller
public class ArticleListController {
	
	@Autowired
	private ChannelService channelService;
	
	@Autowired
	private TagService tagService;
	
	@Autowired
	private Article4TagListService article4TagListService;
	
	private static Logger logger = Logger.getLogger(ArticleListController.class);
	/**
	 * 文章列表
	 */
	@RequestMapping(value = "/article/articleList", method = RequestMethod.GET)
	public String articleList(HttpServletRequest request, HttpServletResponse response)
				throws IOException, BaseCheckedException {
		
		this.setTagNavigateInfo(request);//设置"标签导航"信息
		this.setTagInfoList(request);//设置文章列表中的标签列表信息
		this.setArticle4TagList(request);//设置文章列表中的文章信息
		this.setSearchInfo(request);//设置"上一个请求的查询条件"到页面
		return "/article/article_list";
	}
	/**
	 * 设置"上一个请求的查询条件"到页面
	 */
	private void setSearchInfo(HttpServletRequest request) throws UnsupportedEncodingException {
		String tag = request.getParameter("tag");
		String searchkey = request.getParameter("searchkey");
		String type = request.getParameter("type");
		String status = request.getParameter("status");
		String tagParam;
		if (StringUtil.isEmpty(tag)) {//兼容ie，因为IE中文参数不会自动编码，而chrome,firefox会采用utf-8自动编码
			tagParam = "";
		}else{
			tagParam = URLEncoder.encode(tag , "UTF-8");
		}
		request.setAttribute("searchkey", "null".equals(searchkey) ? "" : searchkey);
		request.setAttribute("type", "null".equals(type) ? "" : type);
		request.setAttribute("tag", "null".equals(tag) ? "" : tag);
		request.setAttribute("tagParam",  tagParam);
		
		String queryStr = "&searchkey=" + searchkey + "&type=" + type;
		if("1".equals(status)){
		    queryStr += "status=1";
		}
		request.setAttribute("queryStr", queryStr);
	}
	
	/**
	 * 设置"标签导航信息":
	 * @param request
	 */
	private void setTagNavigateInfo(HttpServletRequest request) {
		String channelId = request.getParameter("channelId");
		String tag = request.getParameter("tag");
		if (StringUtil.isEmpty(tag)) {// 文章根目录不作设置
			//logger.info("[setTagNavigateInfo]:标签为空,则标签导航信息也为空");
			return;
		}
		TagInfo currentTagInfo = tagService.getByChannelIdAndName(channelId, tag);
		if (currentTagInfo == null) {
			//logger.info("[setTagNavigateInfo]:根据[channelId="+channelId+"],[tag="+tag+"]没找到相应的标签,则标签导航信息为空");
			return;
		}
		String tagTree = currentTagInfo.getTree();
		if (StringUtil.isEmpty(tagTree)) {// 若标签树为空，则直接返回
			return;
		}
		String[] parentTagArr = tagTree.split(",");
		StringBuilder tagTreeUrlBuilder = new StringBuilder();
		for (int i = 0; parentTagArr != null && i < parentTagArr.length; i++) {
			if (StringUtil.isEmpty(parentTagArr[i])) {
				continue;
			}
			tagTreeUrlBuilder.append("<a href=\"/article/articleList.do?channelId=" + channelId
						+ "&tag=" + parentTagArr[i] + "\">" + parentTagArr[i]
						+ "</a><span style=\"color:black\">&gt;&gt;</span>");
		}
		request.setAttribute("currentTag", tag);
		request.setAttribute("tagTreeUr", tagTreeUrlBuilder.toString());
	}
	/**
	 * 设置文章列表中的文章信息
	 */
	private void setArticle4TagList(HttpServletRequest request) throws BaseCheckedException{
		String tag = request.getParameter("tag");
		if (StringUtil.isEmpty(tag)) {// 文章根目录不作设置
			request.setAttribute("isArticleTagRoot", true);
			//logger.info("[setArticle4TagList]:标签为空,则<文章列表中的文章信息>也为空");
			return;
		}
		Article4TagListSearchCriteria article4TagListSearchCriteria = this.setArticle4TagListSearchCriteria(request);
		Page<Article4TagListInfo> article4TagListInfoPage = article4TagListService.pageSearch(article4TagListSearchCriteria);
		request.setAttribute("articleInfoPage", article4TagListInfoPage);
		request.setAttribute("isArticleTagRoot", false);
	}
	
	/**
	 * 设置文章列表中的标签列表信息
	 */
	private void setTagInfoList(HttpServletRequest request){
		String channelId = request.getParameter("channelId");
		String tag = request.getParameter("tag");
		List<TagInfo> tagInfoList = tagService.getChildren(channelId, tag == null ? "" : tag);
		request.setAttribute("tagInfoList", tagInfoList);
	}
	
	/**
	 * 设置articleRoll方法的ArticleSearchCriteria设值代码
	 */
	private Article4TagListSearchCriteria setArticle4TagListSearchCriteria(HttpServletRequest request) throws BaseCheckedException {
		String channelId = request.getParameter("channelId");
		String searchkey = request.getParameter("searchkey");
		String type = request.getParameter("type");
		String tag = request.getParameter("tag");
		String status = request.getParameter("status");
		Article4TagListSearchCriteria article4TagListSearchCriteria = new Article4TagListSearchCriteria();
		article4TagListSearchCriteria.setChannelId(channelId);
		if ( !StringUtil.isEmpty(searchkey) ) {// 作非空判断，防止NullpointException
			searchkey = searchkey.trim();
		}
		if("1".equals(status)){
		    article4TagListSearchCriteria.setStatus(1);
		}
		if ("title".equals(type)) {// 标题
			article4TagListSearchCriteria.setTitle(searchkey);
		} else if ("userid".equals(type)) {// 编辑
			article4TagListSearchCriteria.setUserId(searchkey);
		} else if ("author".equals(type)) {// 作者
			article4TagListSearchCriteria.setAuthor(searchkey);
		} else if ("source".equals(type)) {// 来源
			article4TagListSearchCriteria.setSource(searchkey);
		} else if ("posttime".equals(type)) {// 日期
			try {
			    Date searchDate = DateUtil.parse(searchkey, "yyyy-MM-dd");
			    article4TagListSearchCriteria.setPublishTimeStart(searchDate);
			    article4TagListSearchCriteria.setPublishTimeEnd(DateUtil.getNextDate(searchDate));
			} catch (ParseException e) {
				throw new BaseCheckedException("" , "输入的日期不合法，请输入合法格式:yyyy-MM-dd");
			}
		}
		String pageNo = request.getParameter("pageNo");
		if (!StringUtil.isEmpty(pageNo)) {
			article4TagListSearchCriteria.setPageNo(Integer.parseInt(pageNo));
		}
		//设置排序字段
		article4TagListSearchCriteria.addOrderBy(Article4TagListOrderBy.DAY_NUM_DESC)
										.addOrderBy(Article4TagListOrderBy.POWER_DESC)
										.addOrderBy(Article4TagListOrderBy.POST_TIME_DESC);
		if (!StringUtil.isEmpty(tag)) {
			article4TagListSearchCriteria.addTags(tag);
		}

		return article4TagListSearchCriteria;
	}
	/**
	 * 编辑文章列表的文章信息 
	 */
	@RequestMapping(value = "/article/toEditArticle4TagListPage", method = RequestMethod.GET)
	public String toEditArticle4TagListPage(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		String tag = request.getParameter("tag");
		ChannelInfo channelInfo = channelService.getById(channelId);
		logger.info("开始编辑频道["+channelInfo.getName()+"][channelId="+channelId+"]里标签[tag="+tag+"]的文章[articleId="+articleId+"]");
		Article4TagListInfo article4TagListInfo = article4TagListService.getByPrimaryKey(channelId, tag, Long.parseLong(articleId) );
		request.setAttribute("articleId", articleId);// 文章id
		request.setAttribute("tag", tag);// tag
		request.setAttribute("channelId", channelId);// 频道id
		request.setAttribute("articleInfo", article4TagListInfo);
		return "/article/article_differinfo4tag_edit";
	}
	
	//同一篇文章，不同标签，显示的文章信息不一样；
	@RequestMapping(value = "/article/editArticle4TagList", method = RequestMethod.POST)
	public void editArticle4TagList(HttpServletRequest request, HttpServletResponse response , 
				@ModelAttribute("article4TagListInfo")Article4TagListInfo article4TagListInfo)throws IOException {
		String channelId = request.getParameter("channelId");
		 ChannelInfo channelInfo = (ChannelInfo)request.getSession().getAttribute("channelInfo");
		article4TagListInfo.setChannelInfo(channelInfo);
		article4TagListInfo.setUserId(((UserInfo) request.getSession().getAttribute("userInfo")).getUserId());
		logger.info("提交编辑内容:频道["+channelInfo.getName()+"][channelId="+channelId+"]" +
				"里标签[tag="+article4TagListInfo.getTag()+"]的文章[articleId="+article4TagListInfo.getId()+"]");
		article4TagListService.updateArticle4TagListInfo(article4TagListInfo);
	}
	
	@RequestMapping(value = "/article/updatePower", method = RequestMethod.GET)
	public String updatePower(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		String power = request.getParameter("power");
		String tag = request.getParameter("tag");
		article4TagListService.updatePower(channelId , tag , Long.parseLong(articleId), Integer.parseInt(power));
		return "redirect:/article/articleList.do?channelId=" + channelId+"&tag="+URLEncoder.encode(tag,"UTF-8");
	}

	@RequestMapping(value = "/article/updateDayNum", method = RequestMethod.GET)
	public String updateDayNum(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		String num = request.getParameter("num");
		String tag = request.getParameter("tag");
		article4TagListService.updateDayNum(channelId, tag , Long.parseLong(articleId), Integer.parseInt(num));

		return "redirect:/article/articleList.do?channelId=" + channelId+"&tag="+URLEncoder.encode(tag,"UTF-8");
	}

	@RequestMapping(value = "/article/resetDayNum", method = RequestMethod.GET)
	public String resetDayNum(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		String tag = request.getParameter("tag");
		article4TagListService.resetDayNum(channelId,tag , Long.parseLong(articleId));
		return "redirect:/article/articleList.do?channelId=" + channelId +"&tag="+URLEncoder.encode(tag,"UTF-8");
	}
	
	@RequestMapping(value = "/article4TagList/checkTitle", method = RequestMethod.GET)
	public void checkTitle(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String title = request.getParameter("title");
		String articleId = request.getParameter("articleId");
		String tag = request.getParameter("tag");
		if (article4TagListService.checkTitleIsExisted(channelId , Long.parseLong(articleId) ,title , tag)) {
			response.getWriter().write("exist");
		}
	}
	
	@RequestMapping(value = "/article/deleteArticle4TagList", method = RequestMethod.GET)
	public String deleteArticle4TagList(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		String tag = request.getParameter("tag");
		ChannelInfo channelInfo = channelService.getById(channelId);
		logger.info("删除频道["+channelInfo.getName()+"][channelId="+channelId+"]里标签[tag="+tag+"]的文章[articleId="+articleId+"]");
		article4TagListService.deleteArticle4TagList(channelId, tag, Long.parseLong(articleId) );
		return "redirect:/article/articleList.do?channelId=" + channelId +"&tag="+URLEncoder.encode(tag,"UTF-8");
	}
	
	/**
	 * 根据频道id和文章id批量删除文章列表数据
	 */
	@RequestMapping(value = "/article/deleteByChannelIdAndArticleId", method = RequestMethod.GET)
	public void deleteByChannelIdAndArticleId(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		ChannelInfo channelInfo = channelService.getById(channelId);
		logger.info("删除频道["+channelInfo.getName()+"][channelId="+channelId+"]里文章[articleId="+articleId+"]所有列表文章");
		article4TagListService.deleteByChannelIdAndArticleId(channelId, Long.parseLong(articleId) );
	}
	

	
}
